package com.ruoyi.iot;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.ruoyi.base.service.IDeviceService;
import com.ruoyi.iot.client.NioClient;
import com.ruoyi.iot.utils.WarpUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class IotServer {

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private ScheduledExecutorService scheduledExecutorService;

    @Autowired
    private IotContext iotContext;

    @Value("${iot.port}")
    private Integer port;

    @PostConstruct
    public void start() {
        ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(1), new ThreadFactoryBuilder().setNameFormat("client-server-thread-%d").build(), new ThreadPoolExecutor.AbortPolicy());

        singleThreadPool.execute(() -> {
            EventLoopGroup bossGroup = new NioEventLoopGroup(2, new DefaultThreadFactory("clientServerBoss", true));
            EventLoopGroup workerGroup = new NioEventLoopGroup(6, new DefaultThreadFactory("clientServerWorker", true));
            try {
                ServerBootstrap b = new ServerBootstrap();
                b.group(bossGroup, workerGroup);
                b.channel(NioServerSocketChannel.class);
                b.childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast("messageHandler", getMessageHandler());
                    }
                });
                // 服务器绑定端口监听
                Channel channel = b.bind(port).sync().channel();
                channel.closeFuture().sync();
                log.info("iot server start");
            } catch (Exception e) {
                log.error("", e);
            } finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        });
    }

    public ChannelInboundHandlerAdapter getMessageHandler() {
        return new SimpleChannelInboundHandler<ByteBuf>() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                super.channelActive(ctx);
                String ip = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();
                log.info("channelActive ip: " + ip);
                deviceService.updateDeviceState(ip, 1L);
                iotContext.getNioClientMap().put(ip, new NioClient(ip, ctx.channel(), scheduledExecutorService));
            }

            @Override
            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                super.channelInactive(ctx);
                String ip = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();
                log.info("channelInactive ip: " + ip);
                deviceService.updateDeviceState(ip, 0L);
                NioClient nioClient = iotContext.getNioClientMap().get(ip);
                if (nioClient != null) {
                    nioClient.close();
                }
                iotContext.getNioClientMap().remove(ip);
            }

            @Override
            protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
                String ip = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();
                byte[] data = new byte[byteBuf.readableBytes()];
                byteBuf.readBytes(data);
                log.info("rec from " + ip + ":" + WarpUtil.bytesToHexString(data));
                iotContext.getNioClientMap().get(ip).receiveData(data);
            }
        };
    }
}
